<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>积分管理</el-breadcrumb-item>
	</el-breadcrumb>

	<el-form :inline="true" :model="queryIntegral" class="demo-form-inline">
		<el-form-item label="用户名">
			<el-input v-model="queryIntegral.username" placeholder="请输入用户名" clearable @clear="querydataList" />
		</el-form-item>
		<el-form-item label="昵称">
			<el-input v-model="queryIntegral.nickname" placeholder="请输入昵称" clearable @clear="querydataList" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="querydataList">搜索</el-button>
			<el-button type="danger" @click="batchRemove" :disabled="true">批量删除</el-button>
		</el-form-item>
	</el-form>

	<el-table :data="dataList" border row-key="id" style="width: 100%" @selection-change="handleSelectionChange">
		<el-table-column type="selection" fixed="left" width="40" />
		<el-table-column property="id" label="ID" fixed="left" />
		<el-table-column property="userId" label="用户ID" />
		<el-table-column property="user.nickname" label="昵称" />
		<el-table-column property="user.username" label="用户名" />
		<el-table-column property="score" label="积分" />
		<el-table-column fixed="right" label="操作" min-width="60">
			<template #default="scope">
				<el-button type="success" size="small" @click="view(scope.row)">
					查看
				</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)" :disabled="true">
					删除
				</el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-pagination v-model:current-page="queryIntegral.pageNum" v-model:page-size="queryIntegral.pageSize"
		:page-sizes="[5, 10, 15, 20]" size="default" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<el-dialog :title="title" v-model="dialogFormVisible" width="500px" @close="cancle">
		<el-form :model="formData" label-width="100px">
			<el-form-item label="用户ID">
				<el-input :value="formData.userId" placeholder="用户ID" disabled />
			</el-form-item>
			<el-form-item label="积分值">
				<el-input :value="formData.score" placeholder="积分值" disabled />
			</el-form-item>
			<el-form-item label="关联用户信息">
				<el-input :value="formData.user?.username || ''" placeholder="用户名（只读）" disabled />
			</el-form-item>
			<el-form-item label=" " style="margin-bottom: 0;">
				<el-input :value="formData.user?.nickname || ''" placeholder="昵称（只读）" disabled />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">关闭</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getCurrentInstance, onMounted, reactive, ref } from 'vue';

	// 类型定义
	interface User {
		id ?: number;
		username ?: string;
		nickname ?: string;
	}

	interface Score {
		id ?: number;
		userId : number;
		score : number;
		user ?: User;
		del ?: number;
	}

	// 全局axios
	const axios = getCurrentInstance()!.appContext.config.globalProperties.axios;

	// 查询参数
	const queryIntegral = reactive({
		username: '',
		nickname: '',
		pageNum: 1,
		pageSize: 5,
	});

	// 总数据量
	const total = ref(0);
	// 表格数据列表
	const dataList = ref<Score[]>([]);
	// 批量选择的ID列表
	const multipleSelection = ref<number[]>([]);
	// 对话框标题
	const title = ref('');
	// 对话框显示状态
	const dialogFormVisible = ref(false);
	// 表单数据
	const formData = ref<Score>({
		userId: 0,
		score: 0,
		user: {
			username: '',
			nickname: '',
		},
	});

	// 页面加载时查询数据
	onMounted(() => {
		querydataList();
	});

	// 查询数据列表
	const querydataList = () => {
		axios.get('/score/page', {
			params: {
				...queryIntegral,
				'user.username': queryIntegral.username,
				'user.nickname': queryIntegral.nickname,
			},
		}).then((resp) => {
			if (resp.code === 200) {
				dataList.value = resp.data.list;
				total.value = resp.data.total;
			} else {
				ElMessage.error('数据查询失败: ' + resp.msg);
			}
		}).catch((err) => {
			ElMessage.error('网络错误: ' + err.message);
		});
	};


	const handleSelectionChange = (val : Score[]) => {
		multipleSelection.value = val.map((item) => item.id!);
	};

	// 分页大小变化
	const handleSizeChange = (size : number) => {
		queryIntegral.pageSize = size;
		querydataList();
	};

	// 页码变化
	const handleCurrentChange = (page : number) => {
		queryIntegral.pageNum = page;
		querydataList();
	};

	// 打开查看对话框
	const view = (row : Score) => {
		title.value = '查看积分记录';
		formData.value = {
			...row,
			user: { ...row.user },
		};
		dialogFormVisible.value = true;
	};

	// 取消操作
	const cancle = () => {
		formData.value = {
			userId: 0,
			score: 0,
			user: {
				username: '',
				nickname: '',
			},
		};
		dialogFormVisible.value = false;
	};

	const remove = (id : number) => {
		ElMessageBox.confirm(
			'此操作将永久删除该积分记录，是否继续？',
			'确认删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete(`/score/${id}`)
				.then((resp) => {
					if (resp.code === 200) {
						ElMessage.success('删除成功');
						querydataList();
					} else {
						ElMessage.error('删除失败: ' + (resp.msg || '未知错误'));
					}
				})
				.catch((err) => {
					ElMessage.error('网络错误: ' + err.message);
				});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	const batchRemove = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择需要删除的记录');
			return;
		}
		ElMessageBox.confirm(
			`此操作将删除选中的 ${multipleSelection.value.length} 条记录，是否继续？`,
			'批量删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		).then(() => {
			axios.delete('/score', {
				params: { ids: multipleSelection.value.join(',') },
			}).then((resp) => {
				if (resp.code === 200) {
					ElMessage.success('批量删除成功');
					querydataList();
				} else {
					ElMessage.error('批量删除失败: ' + (resp.msg || '未知错误'));
				}
			}).catch((err) => {
				ElMessage.error('网络错误: ' + err.message);
			});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};
</script>

<style scoped>
	.el-breadcrumb {
		border-bottom: 1px solid #EEEEEE;
		padding: 15px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline {
		padding: 5px 0;
		margin-bottom: 20px;
	}

	.demo-form-inline .el-input {
		width: 175px;
		margin-right: 5px;
	}

	.el-table {
		margin-bottom: 20px;
	}

	.el-pagination {
		text-align: right;
		margin-top: 15px;
	}

	.dialog-footer {
		text-align: right;
	}
</style>